package com.mycompany.project.client;

import java.util.ArrayList;

import marketplace.objects.ClienteBO;
import marketplace.objects.ProveedorBO;
import marketplace.objects.ServicioBO;
import marketplace.objects.UsuarioBO;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.MenuBar;
import com.google.gwt.user.client.ui.MenuItem;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.MenuItemSeparator;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.user.client.ui.Image;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */

public class Inicio implements EntryPoint 
{
	
	private final AdminUsuariosServiceAsync adminUsuarios = (AdminUsuariosServiceAsync)GWT.create(AdminUsuariosService.class);
	private final TransaccionesServiceAsync adminTrans = (TransaccionesServiceAsync)GWT.create(TransaccionesService.class);
	private final AdminServiciosServiceAsync adminServicios = (AdminServiciosServiceAsync)GWT.create(AdminServiciosService.class);
	private final CarroComprasServiceAsync adminCarrito = (CarroComprasServiceAsync)GWT.create(CarroComprasService.class);
	
		
	private PanelServicios panelServicios;
	private PanelContenido panelContenido;
	private PanelCuenta panelCuenta;
	private PanelCarrito panelCarrito;
	private PanelBusqueda panelBusqueda;
	
	//Si hay un cliente loggeado
	boolean logIn = false;
	
	//tipo de cliente
	int tipo = 0;
	
	
	private static Inicio inic;
	
	RootPanel rootPanel = RootPanel.get();
	
	MenuItem mntmMiCuenta;
	MenuItem mntmCarritoDeCompras;
	SuggestBox suggestBox;
	
	private ServicioBO[] lista1;	
	private ServicioBO[] lista2;
	private ServicioBO[] lista3;
	
	private ServicioBO[] itemsCarrito;
	

	private ServicioBO servicioActual=null;
	
	
	public void onModuleLoad() {
		
		
		MenuBar menuBar = new MenuBar(false);
		rootPanel.setSize("540px", "340px");
		rootPanel.add(menuBar, 10, 37);
		menuBar.setSize("665px", "19px");
		
		MenuItem mntmLogin = new MenuItem("Login", false, new Command() {
			public void execute() {
				PanelLogin login = new PanelLogin();
				login.show();
				login.setPopupPosition(100, 100);
			}					
			
		});
		menuBar.addItem(mntmLogin);
		
		MenuItemSeparator separator = new MenuItemSeparator();
		menuBar.addSeparator(separator);
		
		MenuItem mntmRegistrarse = new MenuItem("Registrarse", false, new Command() {
			public void execute() {
				Registro panelRegistro = new Registro();
				panelRegistro.show();			
				panelRegistro.setPopupPosition(100, 100);
				
			}
		});
		menuBar.addItem(mntmRegistrarse);
		
		MenuItemSeparator separator_2 = new MenuItemSeparator();
		menuBar.addSeparator(separator_2);
		
		MenuItem mntmBandejaDeEntrada = new MenuItem("Bandeja de Entrada", false, new Command() {
			public void execute() {
				DialogoExcepcion diag = new DialogoExcepcion();
				diag.show();
				
			}
		});
		mntmBandejaDeEntrada.setEnabled(false);
		menuBar.addItem(mntmBandejaDeEntrada);
		
		MenuItemSeparator separator_1 = new MenuItemSeparator();
		menuBar.addSeparator(separator_1);
		
		mntmMiCuenta = new MenuItem("Mi Cuenta", false, new Command() {
			public void execute() {
				if(logIn==true){
				panelCuenta = new PanelCuenta();
				rootPanel.clear();
				rootPanel.add(panelCuenta);
				}
				else
				{
					DialogoVerificarLogin login = new DialogoVerificarLogin();
					login.show();
					login.setPopupPosition(100, 100);
				}
			}					
			
		});
		menuBar.addItem(mntmMiCuenta);
		
		MenuItemSeparator separator_3 = new MenuItemSeparator();
		menuBar.addSeparator(separator_3);
		
		mntmCarritoDeCompras = new MenuItem("Carrito de Compras", false, new Command() {
			public void execute() {
				
				if(logIn==true){
				panelCarrito = new PanelCarrito();
				panelCarrito.logIn(logIn);
				rootPanel.clear();
				rootPanel.add(panelCarrito);
				}
				else
				{
					DialogoVerificarLogin login = new DialogoVerificarLogin();
					login.show();
					login.setPopupPosition(100, 100);
				}
			}					
			
		});
		menuBar.addItem(mntmCarritoDeCompras);
		
		TextArea txtrNoticiasDelSistema = new TextArea();
		txtrNoticiasDelSistema.setName("Noticias");
		txtrNoticiasDelSistema.setReadOnly(true);
		txtrNoticiasDelSistema.setTitle("Noticias");
		txtrNoticiasDelSistema.setText("Noticias del sistema\r\n");
		rootPanel.add(txtrNoticiasDelSistema, 10, 128);
		txtrNoticiasDelSistema.setSize("493px", "75px");
		
		Button btnVerServicio = new Button("Servicios");
		btnVerServicio.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent arg0) {
				panelServicios = new PanelServicios();
				rootPanel.clear();
				rootPanel.add(panelServicios);	
				
			}
		});
		rootPanel.add(btnVerServicio, 23, 215);
		btnVerServicio.setSize("100px", "28px");
		
		Button btnContenidos = new Button("Contenidos");
		btnContenidos.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent arg0) {
				panelContenido = new PanelContenido();
				rootPanel.clear();
				rootPanel.add(panelContenido);	
			}
		});
		rootPanel.add(btnContenidos, 146, 215);
		btnContenidos.setSize("100px", "28px");
		
		Label lblBuscadorDeServicios = new Label("Buscador");
		rootPanel.add(lblBuscadorDeServicios, 24, 255);
		
		suggestBox = new SuggestBox();
		rootPanel.add(suggestBox, 107, 251);
		suggestBox.setSize("255px", "16px");
		
		Button btnIr = new Button("Ir");
		btnIr.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent arg0) {
				panelBusqueda = new PanelBusqueda();
				panelBusqueda.buscar(suggestBox.getText());
				rootPanel.clear();
				rootPanel.add(panelBusqueda);	
			}
		});
		rootPanel.add(btnIr, 394, 249);
		btnIr.setSize("100px", "28px");
		
		Button btnForo = new Button("Foro");
		btnForo.setEnabled(false);
		rootPanel.add(btnForo, 269, 215);
		btnForo.setSize("100px", "28px");
		
		Button btnCalendario = new Button("Calendario");
		btnCalendario.setEnabled(false);
		rootPanel.add(btnCalendario, 392, 215);
		btnCalendario.setSize("100px", "28px");
		
		Image image = new Image("Logo.PNG");
		rootPanel.add(image, 10, 0);
		image.setSize("166px", "28px");
		
		Label lblMarketplaceDeTurismo = new Label("Marketplace de Turismo Ecol\u00F3gico Su equipo de trabajo ha sido contratado por el Grupo Empresarial Los Alpes para desarrollar un Marketplace de Turismo Ecol\u00F3gico");
		lblMarketplaceDeTurismo.setStyleName("a");
		rootPanel.add(lblMarketplaceDeTurismo, 10, 64);
		lblMarketplaceDeTurismo.setSize("499px", "47px");
		
		inic = this;
	}
	
	public void verificarLogin(String user, String pass)
	{
		adminUsuarios.validarUsuario(user, pass, new AsyncCallback<Boolean>() 
				{
		    // This method will be called if the service call fails   
		    public void onFailure(Throwable caught)
		    {
		      // Show a message informing the user why the call failed   
		      Window.alert("Failed to get response from server" + caught.getMessage());
		    }
		    // This method will be called if the service call succeeds   
		    public void onSuccess(Boolean result)
		    {
		      // Get the service call result and cast it to the desired type and display it
		      logIn= result;
		     }
		});
		
		if(logIn==false)
		{
			DialogoExcepcion exce = new DialogoExcepcion();
			exce.show();
			exce.setPopupPosition(100, 100);
		}
		else
		{
			adminUsuarios.consultarUsuario(user,new AsyncCallback<UsuarioBO>() 
					{
			    // This method will be called if the service call fails   
			    public void onFailure(Throwable caught)
			    {
			      // Show a message informing the user why the call failed   
			      Window.alert("Failed to get response from server" + caught.getMessage());
			    }
			    // This method will be called if the service call succeeds   
			    public void onSuccess(UsuarioBO result)
			    {
			      // Get the service call result and cast it to the desired type and display it
			    	
			    	if(result.getTipo().equals(UsuarioBO.CLIENTE))
			    	{
			    		tipo =1;
			      	}	
			    	else if(result.getTipo().equals(UsuarioBO.PROVEEDOR))
			    	{
			    		tipo =2;
			      	}	
			     }
			});
		}		
	}
	
	public void mostrarDialogoVerificacion()
	{
		DialogoVerificarLogin login = new DialogoVerificarLogin();
		login.show();
		login.setPopupPosition(100, 100);
	}
	
	public static Inicio darInstancia()
	{
		if (inic ==null) {
			inic = new Inicio();
		}
		
		return inic;
	}
		
	/**
	 * 
	 */
	public void abrirMiCuenta() 
	{
		mntmMiCuenta.getCommand().execute();		
	}
	
	/**
	 * 
	 */
	public void abrirCarritoCompra() 
	{
		mntmCarritoDeCompras.getCommand().execute();		
	}

	/**
	 * 
	 * @param nNom
	 * @param nLogin
	 * @param nPass
	 * @param nCorreo
	 * @param nTel
	 * @param nDir
	 */
	public void registrarProveedor(String nNom, String nLogin, String nPass, String nCorreo, String nTel, String nDir) 
	{
		ProveedorBO proveedor = new ProveedorBO(nNom, nCorreo, nTel, nLogin, nPass, nDir);
		adminUsuarios.registrarUsuario(proveedor, UsuarioBO.PROVEEDOR, new AsyncCallback<Void>() 
				{
		    // This method will be called if the service call fails   
		    public void onFailure(Throwable caught)
		    {
		      // Show a message informing the user why the call failed   
		      Window.alert("Failed to get response from server" + caught.getMessage());
		    }
			@Override
			public void onSuccess(Void arg0) {				
				// TODO Auto-generated method stub
				 Window.alert("Su registro fue satifastorio");
			}
		});
		// TODO Auto-generated method stub		
	}
	
	/**
	 * 
	 * @param nombre
	 * @param nlogin
	 * @param pass
	 * @param correo
	 * @param tel
	 */
	public void registrarCliente(String nombre, String nlogin, String pass, String correo, String tel) 
	{
		ClienteBO client = new ClienteBO(nombre, correo, tel, nlogin, pass);		
		adminUsuarios.registrarUsuario(client, UsuarioBO.CLIENTE, new AsyncCallback<Void>() 
				{
		    // This method will be called if the service call fails   
		    public void onFailure(Throwable caught)
		    {
		      // Show a message informing the user why the call failed   
		      Window.alert("Failed to get response from server" + caught.getMessage());
		    }
			@Override
			public void onSuccess(Void arg0) {				
				// TODO Auto-generated method stub
				 Window.alert("Su registro fue satifastorio");
			}
		});
		// TODO Auto-generated method stub		
	}

	/**
	 * 
	 * @return
	 */
	public String[] darCategorias()
	{
		String[] lista = new String[3];
		lista[0]=ServicioBO.ALIMENTACION;
		lista[1]=ServicioBO.ALOJAMIENTO;
		lista[2]=ServicioBO.TOUR;
		return lista;
	}
	
	public String[] darCriterio()
	{
		String[] lista = new String[4];
		lista[0]= "Precio";
		lista[1]= "Proveedor";
		lista[2]= "Nombre";
		return lista;		
	}
	
	/**
	 * 
	 */
	public void darServicios()
	{		
		adminServicios.consultarServiciosPorTipo(ServicioBO.ALIMENTACION,  new AsyncCallback<ArrayList<ServicioBO>>() 
			{
		    // This method will be called if the service call fails   
		    public void onFailure(Throwable caught)
		    {
		      // Show a message informing the user why the call failed   
		      Window.alert("Failed to get response from server" + caught.getMessage());
		    }
		    // This method will be called if the service call succeeds   
		    public void onSuccess(ArrayList<ServicioBO> result)
		    {
		    	ServicioBO[] lista = new ServicioBO[result.size()];
		    	int x = 0;
		    	for (ServicioBO servicioBO : result) 
		    	{
		    		lista[x] = servicioBO;
		    		x++;
				}
		    	Inicio.this.lista1 = lista;
		      // Get the service call result and cast it to the desired type and display it
		     }
		});
		adminServicios.consultarServiciosPorTipo(ServicioBO.ALOJAMIENTO,  new AsyncCallback<ArrayList<ServicioBO>>() 
				{
			    // This method will be called if the service call fails   
			    public void onFailure(Throwable caught)
			    {
			      // Show a message informing the user why the call failed   
			      Window.alert("Failed to get response from server" + caught.getMessage());
			    }
			    // This method will be called if the service call succeeds   
			    public void onSuccess(ArrayList<ServicioBO> result)
			    {
			    	ServicioBO[] lista = new ServicioBO[result.size()];
			    	int x = 0;
			    	for (ServicioBO servicioBO : result) 
			    	{
			    		lista[x] = servicioBO;
			    		x++;
					}
			    	Inicio.this.lista2 = lista;
			      // Get the service call result and cast it to the desired type and display it
			     }
			});
		adminServicios.consultarServiciosPorTipo(ServicioBO.TOUR,  new AsyncCallback<ArrayList<ServicioBO>>() 
				{
			    // This method will be called if the service call fails   
			    public void onFailure(Throwable caught)
			    {
			      // Show a message informing the user why the call failed   
			      Window.alert("Failed to get response from server" + caught.getMessage());
			    }
			    // This method will be called if the service call succeeds   
			    public void onSuccess(ArrayList<ServicioBO> result)
			    {
			    	ServicioBO[] lista = new ServicioBO[result.size()];
			    	int x = 0;
			    	for (ServicioBO servicioBO : result) 
			    	{
			    		lista[x] = servicioBO;
			    		x++;
					}
			    	Inicio.this.lista3 = lista;
			      // Get the service call result and cast it to the desired type and display it
			     }
			});
	}

	/**
	 * 
	 * @return
	 */
	public ServicioBO[] getServiciosAlimentacion()
	{
		return lista1;
	}

	/**
	 * 
	 * @return
	 */
	public ServicioBO[] getServiosAlojamiento()
	{
		return lista2;
	}
	/**
	 * 
	 * @return
	 */
	public ServicioBO[] getServiciosTour()
	{
		return lista3;
	}

	public ServicioBO buscarServicioCriterio(String critec, String aBuscar)
	{
		adminServicios.consultarServicioPorParametro(critec, aBuscar,new AsyncCallback<ArrayList<ServicioBO>>() 
				{
		    // This method will be called if the service call fails   
		    public void onFailure(Throwable caught)
		    {
		      // Show a message informing the user why the call failed   
		      Window.alert("Failed to get response from server" + caught.getMessage());
		    }
		    // This method will be called if the service call succeeds   
		    public void onSuccess(ArrayList<ServicioBO> result)
		    {
		    	ServicioBO[] lista = new ServicioBO[result.size()];
		    	servicioActual = lista[0];
		      // Get the service call result and cast it to the desired type and display it
		     }
		});
		
		return servicioActual;
	}
	
}
